<?php
declare(strict_types=1);


namespace App\Mall\Mapper;

use App\Mall\Model\MallGoodsPrice;
use App\Mall\Model\MallGoodsSpec;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;

/**
 * 商品规格Mapper类
 */
class MallGoodsSpecMapper extends AbstractMapper
{
    /**
     * @var MallGoodsSpec
     */
    public $model;

    public function assignModel()
    {
        $this->model = MallGoodsSpec::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        if (isset($params['goods_id']) && filled($params['goods_id'])) {
            $query->where('goods_id', '=', $params['goods_id']);
        }
        return $query->with(['price']);
    }

    public function save(array $data): mixed
    {
        $id = parent::save($data);
        if ($id) $this->price($data['price'], $data['goods_id'], $id);
        return $id;
    }

    public function update(mixed $id, array $data): bool
    {
        $s = parent::update($id, $data);
        if ($s) $this->price($data['price'], $data['goods_id'], $id);
        return $s;
    }

    public function price(array $data, int $goods_id, int $spec_id): bool
    {
        MallGoodsPrice::query()->where(['spec_id' => $spec_id, 'goods_id' => $goods_id])->delete();
        $in = [];
        if (!MallGoodsSpec::query()->where(['goods_id' => $goods_id, 'is_default' => 1])->exists())
            $this->model::query()->where(['id' => $spec_id])->update(['is_default' => 1]);
        foreach ($data as $v) {
            $in[] = [
                'goods_id' => $goods_id,
                'spec_id' => $spec_id,
                'symbol' => $v['symbol'],
                'price' => $v['price'],
            ];
        }
        if ($in) MallGoodsPrice::query()->insert($in);
        return true;
    }
}